package com.huishen.edrivenew.ui;

import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshExpandableListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.huishen.edrivenew.AppContext;
import com.huishen.edrivenew.Constants;
import com.huishen.edrivenew.R;
import com.huishen.edrivenew.adapter.AppoCoachListApdater;
import com.huishen.edrivenew.adapter.TimeClassSchoolListener;
import com.huishen.edrivenew.base.BaseActivity;
import com.huishen.edrivenew.bean.CoachBean;
import com.huishen.edrivenew.bean.CoachListBean;
import com.huishen.edrivenew.bean.DateBean;
import com.huishen.edrivenew.bean.LessonTimeBean;
import com.huishen.edrivenew.bean.ListLessonTimeBean;
import com.huishen.edrivenew.net.JsonResponseHandler;
import com.huishen.edrivenew.net.NetApi;
import com.huishen.edrivenew.widget.MassageListener;
import com.huishen.edrivenew.widget.MessageDialog;
import com.huishen.edrivenew.widget.MessageDialogNew;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * 
 * @author wu
 * @version 1.0
 * @created 2015/7/1
 */
public class RequestCoachListActivity  extends BaseActivity implements OnRefreshListener2<ExpandableListView>{


    @InjectView(R.id.header_title)
    public TextView title;
    @InjectView(R.id.header_back)
    public ImageButton back;
    
    @InjectView(R.id.appoint_tv_time)
    public TextView subText;
    
    @InjectView(R.id.appoint_tv_week)
    public TextView timeText;

    @InjectView(R.id.appoint_expandablelist)
    public PullToRefreshExpandableListView mPullRefreshListView;

    private AppoCoachListApdater adapter;

    private DateBean currentDateBean;
    
    private CoachListBean coachList = new CoachListBean();
    private String[] sub = new String[] { "", "科目一", "科目二", "科目三", "科目四" };
    private int page = 1;
    
    private MessageDialogNew mdialog;
    private MessageDialog mdialogC;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_apocoalist);
        ButterKnife.inject(this);

        setDate();
        
        // 请求第一页
        page = 1;
        request(page);
    }

    private void setDate() {
        title.setText("预约教练");
        
        if(AppContext.getInstance().dateBean != null) {
            currentDateBean = AppContext.getInstance().dateBean;
            
            if(currentDateBean.type == 2) {
                subText.setText("科目二");
            } else if(currentDateBean.type == 3) {
                subText.setText("科目三");
            }
            timeText.setText(currentDateBean.getDateString());
        }
    }


  //设置listview
    private void setListDate() {
        if(adapter != null) {
            reSetListDate();
            return;
        }
        adapter = new AppoCoachListApdater(this, coachList, listener);
        mPullRefreshListView.getRefreshableView().setAdapter(adapter);
        
        mPullRefreshListView.getRefreshableView().setOnGroupExpandListener(new OnGroupExpandListener() {
            //展开事件
            @Override
            public void onGroupExpand(int groupPosition) {
                for (int i = 0; i < adapter.getGroupCount(); i++) {    
                    if (groupPosition != i) {    
                        //  关闭其他item页
                        mPullRefreshListView.getRefreshableView().collapseGroup(i);
                    }    
                }  
                // 
                ListLessonTimeBean timeBean = adapter.getChild(groupPosition, 0);
                if(timeBean == null) {
                    getcoaDate(groupPosition);
                }
                
            }
        });
        
        mPullRefreshListView.setMode(Mode.BOTH);
        mPullRefreshListView.setOnRefreshListener(this);
        setLoadMoreText(false);
    }
    
    private void reSetListDate() {
        setLoadMoreText(coachList.hasDone);
        adapter.setData();
        if(coachList.currPage == 1) {
            adapter.claenChild();
        }
        
        adapter.notifyDataSetChanged();
    }
    
    private void setCoaTimeList(int index, ListLessonTimeBean timeBean) {
        adapter.setChild(index, timeBean);
        adapter.notifyDataSetChanged();
    }
    
    
    private void setLoadMoreText(boolean isDone) {
        if(isDone) {
            mPullRefreshListView.getLoadingLayoutProxy(false, true).setPullLabel("已加载全部");  
            mPullRefreshListView.getLoadingLayoutProxy(false, true).setRefreshingLabel("已加载全部");  
            mPullRefreshListView.getLoadingLayoutProxy(false, true).setReleaseLabel("已加载全部");
        } else {
            mPullRefreshListView.getLoadingLayoutProxy(false, true).setPullLabel("上拉加载...");  
            mPullRefreshListView.getLoadingLayoutProxy(false, true).setRefreshingLabel("正在加载...");  
            mPullRefreshListView.getLoadingLayoutProxy(false, true).setReleaseLabel("放开加载更多...");
        }
    }
    
    
    
    private TimeClassSchoolListener listener = new TimeClassSchoolListener() {
        @Override
        public void setOnClick(LessonTimeBean timeBean, CoachBean coach, int code) {
            if (code == 0) {
                showActionAppoint(timeBean, coach);
            } else {
                showActionCancel(timeBean, coach);
            }
        }
    };
    
    
    private void showActionAppoint(final LessonTimeBean timeBean, final CoachBean coach) {
        
        mdialog = new MessageDialogNew(this, sub[currentDateBean.type], coach.toString(), currentDateBean.getDateString() + 
            "   " + timeBean.duringDate, timeBean.money +"", AppContext.getInstance().outline.project
               , new MassageListener() {
            @Override
            public void setCommitClick() {
                if(AppContext.getInstance().studentBean.balance < timeBean.money) {
                    showMoney();
                    return;
                }
                
                actionAppoint(timeBean, coach.id);
            }
            @Override
            public void setCancelClick() {
            }
        });
        mdialog.show();
    }
    private void showActionCancel(final LessonTimeBean timeBean,final CoachBean coach) {
        mdialogC = new MessageDialog(this, "您确定取消预约的时间吗？", "", true,
            new MassageListener() {
                @Override
                public void setCommitClick() {
                    actionCancel(timeBean, coach.id);
                }
                @Override
                public void setCancelClick() {
                }
            });
        mdialogC.setCancelHide();
        mdialogC.setCryicon(false);
        mdialogC.show();
    }
    
    private void showMoney() {
        mdialogC = new MessageDialog(this, "", "亲 您的帐户余额不足，请到驾校进行充值", true,
            new MassageListener() {
                @Override
                public void setCommitClick() {
                }
                @Override
                public void setCancelClick() {
                }
            });
        mdialogC.setCancelHide();
        mdialogC.setCryicon(true);
        mdialogC.show();
    }
    
    
    // 请求数据
    private void request(int currpage) {
        if(currpage == 1) {
            showDialog();
        }
        NetApi.queryDirectCoachPage(this, new JsonResponseHandler() {
            @Override
            public void onSuccess(int code, JSONObject jsonObj, Object[] args) {
                try {
                    if (code == Constants.N_SUCCESS) {
                        // 获取list数据
                        JSONObject listObj = jsonObj.getJSONObject("coachList");
                        CoachListBean newList = (CoachListBean) CoachListBean.parseJson(listObj);
                        coachList.addDate(newList);
                        setListDate();
                        
                        page++;
                    } else {
                        showToast("获取数据失败！");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    showToast("获取数据失败！");
                }
                dismissDialog();
                mPullRefreshListView.onRefreshComplete();
            }
            @Override
            public void onFailure(int code, String errorMessage, Object[] args) {
                dismissDialog();
                mPullRefreshListView.onRefreshComplete();
                showToast("获取数据失败！");
            }
            @Override
            public void onSessionFailure() {
                dismissDialog();
                mPullRefreshListView.onRefreshComplete();
                super.onSessionFailure();
            }
        }, currentDateBean.type, currpage);
    }
    
    // 获取教练当天数据
    private void getcoaDate(final int index) {
        showDialog();
        int id = coachList.rows.get(index).id;
        NetApi.queryCoachlessonTimeStatus(this, new JsonResponseHandler() {
            @Override
            public void onSuccess(int code, JSONObject jsonObj, Object[] args) {
                try {
                    ListLessonTimeBean listTime = (ListLessonTimeBean) ListLessonTimeBean.parseJson(jsonObj);
                    setCoaTimeList(index, listTime);
                } catch (Exception e) {
                    e.printStackTrace();
                    showToast("获取数据失败，请稍后再试！");
                }
                dismissDialog();
            }
            @Override
            public void onFailure(int code, String errorMessage, Object[] args) {
                dismissDialog();
                showToast("获取数据失败，请稍后再试！");
            }
            @Override
            public void onSessionFailure() {
                dismissDialog();
                super.onSessionFailure();
            }
        }, id+"", currentDateBean.getDateString());
    }
    
    private void actionAppoint(LessonTimeBean timeBean, int coachId) {
        showDialog();
        String outlineS = null;
        String lessonID = null;
        if(AppContext.getInstance().outline != null) {
            outlineS = AppContext.getInstance().outline.outlineId + "";
            lessonID = AppContext.getInstance().outline.invalidlessonId + "";
        }
        
        NetApi.addStulessonTime(this, new JsonResponseHandler(){
            @Override
            public void onSuccess(int code, JSONObject jsonObj, Object[] args) {
                dismissDialog();
                try {
                    if (code == Constants.N_SUCCESS) {
                        showToast("预约成功！");
                        updateDate();
                    } else {
                        showToast("预约失败，请稍后再试！");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    showToast("预约失败，请稍后再试！");
                }
            }

            @Override
            public void onFailure(int code, String errorMessage, Object[] args) {
                dismissDialog();
                showToast("操作失败，请稍后再试！");
            }
            @Override
            public void onSessionFailure() {
                dismissDialog();
                super.onSessionFailure();
            }
        }, coachId+"", currentDateBean.getDateString(), timeBean.duringDate, 
        timeBean.money+"", currentDateBean.type+"", outlineS, lessonID);
    }
    private void actionCancel(LessonTimeBean timeBean, int coachId) {
        showDialog();
        NetApi.updateStulessonTimeSattus(this, new JsonResponseHandler(){
            @Override
            public void onSuccess(int code, JSONObject jsonObj, Object[] args) {
                dismissDialog();
                try {
                    if (code == Constants.N_SUCCESS) {
                        showToast("取消成功！");
                        updateDate();
                    } else {
                        showToast("操作失败，请稍后再试！");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    showToast("操作失败，请稍后再试！");
                }
            }

            @Override
            public void onFailure(int code, String errorMessage, Object[] args) {
                dismissDialog();
                showToast("操作失败，请稍后再试！");
            }
            @Override
            public void onSessionFailure() {
                dismissDialog();
                super.onSessionFailure();
            }
        }, coachId+"", currentDateBean.getDateString(), timeBean.duringDate, 
        currentDateBean.type+"", timeBean.money+"");
    }
    

    
    
    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ExpandableListView> refreshView) {
        for (int i = 0; i < adapter.getGroupCount(); i++) {    
            mPullRefreshListView.getRefreshableView().collapseGroup(i);
        }  
        page = 1;
        request(page);
    }
    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ExpandableListView> refreshView) {
        for (int i = 0; i < adapter.getGroupCount(); i++) {    
            mPullRefreshListView.getRefreshableView().collapseGroup(i);
        } 
        if(coachList.hasDone) {
            mPullRefreshListView.onRefreshComplete();
        } else {
            request(page);
        }
    }
    
    private void updateDate() {
        toMain();
    }

    @OnClick(R.id.header_back)
    public void toMain() {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        this.startActivity(intent);
        this.finish();
    }
    

}
